package com.njit.farm.service.impl;

import com.njit.farm.dao.FLandMapper;
import com.njit.farm.dataobject.FLand;
import com.njit.farm.model.*;
import com.njit.farm.service.LandService;
import com.njit.farm.util.IDUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class LandServiceImpl implements LandService {

    @Resource
    FLandMapper fLandMapper;

    @Override
    public Result add(Land land) {

        Result result = new Result();

        FLand fLand = new FLand();
        fLand.setuId(land.getuId());
        fLand.setlName(land.getName());
        fLand.setlId(IDUtils.uuid());
        fLand.setlStage(LandState.SEEDLING.getState());


        fLandMapper.insert(fLand);

        result.setSucc(true);
        return result;
    }

    @Override
    public Result update(Land land) {

        Result result = new Result();

        FLand fLand = new FLand();
        fLand.setlId(land.getId());
        fLand.setlName(land.getName());
        fLand.setlStage(land.getStage());
        fLand.setlTemperature(land.getTemperature());
        fLand.setlHumidity(land.getHumidity());
        fLand.setlLightpower(land.getLightPower());
        fLand.setlCo2(land.getCo2());
        fLand.setlUrlAr(land.getUrlAr());

        List<String> seeds = land.getSeeds();
        StringBuilder sb = new StringBuilder();
        if (seeds != null) {
            for(int i=0;i<seeds.size();i++){
                sb.append(seeds.get(i));
                if(i<seeds.size()-1){
                    sb.append(",");
                }
            }
        }
        fLand.setlSeeds(sb.toString());

        List<String> tags = land.getTags();
        sb = new StringBuilder();
        if (tags != null) {
            for(int i=0;i<tags.size();i++){
                sb.append(tags.get(i));
                if(i<tags.size()-1){
                    sb.append(",");
                }
            }
        }
        fLand.setlTags(sb.toString());

        fLand.setuId(land.getuId());

        fLandMapper.updateByPrimaryKey(fLand);

        result.setSucc(true);
        return result;
    }

    @Override
    public Result getByUserId(String uid) {
        Result result = new Result();
        List<FLand> fLands = fLandMapper.selectByUserId(uid);
        List<Land> landList = new ArrayList<>();

        for (FLand fLand : fLands) {
            landList.add(fLand.toModel());
        }
        result.setSucc(true);
        result.setData(landList);
        return result;
    }
}
